import 'package:barcode_scan/barcode_scan.dart';
import 'package:erp/Entity/Product.dart';
import 'package:erp/Entity/ProductBalance.dart';
import 'package:erp/Entity/PurchaseOrder.dart';
import 'package:erp/Entity/ProductDetailAtPurchaseOrSell.dart';
import 'package:erp/Entity/Supplier.dart';
import 'package:erp/Entity/WareHouse.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/Extensions/DateTime.dart';
import 'package:erp/Extensions/DialogResult.dart';
import 'package:erp/Store/AccountStore.dart';
import 'package:erp/Store/ProductStore.dart';
import 'package:erp/UI/Components/EmbeddableStatefulWidget.dart';
import 'package:erp/UI/Components/EventfulState.dart';
import 'package:erp/UI/Components/ListDividerGenerator.dart';
import 'package:erp/UI/Components/LogoScaffold.dart';
import 'package:erp/UI/Components/MessageDialog.dart';
import 'package:erp/UI/Components/ProgressDialog.dart';
import 'package:erp/UI/Pages/BasicInformationManagementPages/ProductManagementPages/ProductInfoManagement.dart';
import 'package:erp/UI/Pages/BasicInformationManagementPages/SupplierPages/SupplierInformationPage.dart';
import 'package:erp/UI/Pages/BasicInformationManagementPages/WareHousePages/WareHousePage.dart';
import 'package:erp/global.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart' show DateFormat;


class PurchasePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) => PurchasePageStateful();
}

class PurchasePageStateful extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => PurchasePageState();
}

class PurchasePageState extends EventfulState<PurchasePageStateful> {
  Icon supplierChangeIcon = Icon(Icons.add);
  bool supplierChangeExpansionIsExpanded = false;
  bool canSelectPurchase = false;
  bool productPanelExpanded = false;
  bool wareHousePanelExpanded = false;
  var selectedProducts = List<ProductDetailAtPurchaseOrSell>();
  Supplier selectedSupplier;
  WareHouse selectedWareHouse;
  var progressDialog = ProgressDialog();
  @override
  void initState() {
    progressDialog.context = context;
    eventIds = [
      globalBus.subscribe(Events.PURCHASE_INSERT_REQUEST, (bus, data){
        progressDialog.show();
      }),
      globalBus.subscribe(Events.PURCHASE_INSERT_ERROR, (bus, error){
        progressDialog.close();
        showMessageDialog(context, title: "كىرگۈزۈشتە خاتالىق كۆرۈلدى", content: error.toString());
      }),
      globalBus.subscribe(Events.PURCHASE_INSERT_SUCCESS, (bus, data){
        progressDialog.close();
        Navigator.of(context).pop(null);
      })
    ];
    super.initState();
  }

  void productSelected(Product result)async {
    var data = DialogResult(
        data: ProductDetailAtPurchaseOrSell.fromProduct(result),
        mode: DialogMode.Creation
    );

    await showFillParameterDialog(context, data);
    if (!data.success) return;
    var oldProduct = selectedProducts.singleWhere((item) => item.id == data.data.id, orElse: () => null);

    if (oldProduct == null) {
      oldProduct = data.data;
      selectedProducts.add(oldProduct);
    }
    else
      oldProduct.count += data.data.count;
  }

  @override
  Widget build(BuildContext context) {
    return LogoScaffold(
      title: "مال كىرگۈزۈش",
      assetsLogoName: "assets/pictures/import.png",
      heroName: "PurchasePageLogoHero",
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.save),
        onPressed: () {
          var purchaseOrder = PurchaseOrder();
          purchaseOrder.products = selectedProducts;
          showConfirmDialog(purchaseOrder);
        },
      ),
      contentDelegate: SliverChildListDelegate([
        Padding(
          padding: EdgeInsets.all(10.0),
          child: ExpansionPanelList(
            children: <ExpansionPanel>[
              ExpansionPanel(
                headerBuilder: (context, expanded) =>
                    Align(
                      child: Padding(
                          padding: EdgeInsets.only(right: 15.0),
                          child: Row(
                            children: <Widget>[
                              Expanded(
                                child: Text("مال تەمىنلىگۈچى تاللاي"),
                              ),
                              Switch(
                                  value: canSelectPurchase,
                                  onChanged: (value) {
                                    setState(() {
                                      canSelectPurchase = value;
                                      if (canSelectPurchase && !supplierChangeExpansionIsExpanded) {
                                        supplierChangeExpansionIsExpanded = value;
                                      }
                                    });
                                  })
                            ],
                          )),
                      alignment: Alignment(1.0, 0.0),
                    ),
                isExpanded: supplierChangeExpansionIsExpanded,
                body: Padding(
                  padding: EdgeInsets.all(15.0),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: Text("مال تەمىنلىگۈچى"),
                      ),
                      Text(selectedSupplier?.name ?? ""),
                      IconButton(
                        icon: supplierChangeIcon,
                        onPressed: () async {
                          var result = await Navigator.of(context).push(
                              MaterialPageRoute(builder: (context) => SupplierInformationPage(selectionMode: true, title: "مال تەمىنلىگۈچىنى تاللاڭ",)));
                          if (result != null) {
                            setState(() {
                              supplierChangeIcon = Icon(Icons.autorenew);
                              this.selectedSupplier = result;
                            });
                          }
                        },
                      )
                    ],
                  ),
                ),
              ),
            ],
            expansionCallback: (index, expanded) {
              setState(() {
                supplierChangeExpansionIsExpanded = !expanded;
              });
            },
          ),
        ),
        Padding(
          padding: EdgeInsets.all(10.0),
          child: Column(
            children: <Widget>[
              ExpansionPanelList(
                expansionCallback: (index, expanded) {
                  setState(() {
                    productPanelExpanded = !expanded;
                  });
                },
                children: <ExpansionPanel>[
                  ExpansionPanel(
                      headerBuilder: (context, expanded) {
                        return Container(
                          alignment: Alignment(1.0, 0.0),
                          padding: EdgeInsets.symmetric(horizontal: 15.0),
                          child: Text("ئەكىرمەكچى بولغان تاۋارلار"),
                        );
                      },
                      body: Column(
                          children: ListDividerGenerator(
                              List.generate(selectedProducts.length, (index) =>
                                      ListTile(
                                        title: Text(selectedProducts[index].nameUg ?? selectedProducts[index].nameZh),
                                        subtitle: Text("${selectedProducts[index].count}"),
                                        trailing: Wrap(
                                          children: <Widget>[
                                            IconButton(
                                                icon: Icon(Icons.edit),
                                                onPressed: () async {
                                                  var data = DialogResult(data: selectedProducts[index], mode: DialogMode.Update);
                                                  await showFillParameterDialog(context, data);
                                                }),
                                            IconButton(
                                                icon: Icon(Icons.delete_forever),

                                                onPressed: () {
                                                  setState(() {
                                                    selectedProducts.removeAt(index);
                                                  });
                                                }),
                                          ],
                                        ),
                                        leading: Image.asset("assets/pictures/boxes.png", width: 40.0, height: 40.0,),
//                                        leading: Image.network(
//                                          selectedProducts[index].imgUrl,
//                                          width: 40.0,
//                                          height: 40.0,
//                                        ),
                                      ))
                                ..add(Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    FlatButton(
                                      //// For Select Product
                                        onPressed: () async {
                                          var result = await Navigator.of(context).push<Product>(MaterialPageRoute(builder: (context) => ProductInfoManagement(isSelectionMode: true, title: "ئەكىرمەكچى بولغان تاۋارنى تاللاڭ",)));
                                          if (result == null) return;
                                          productSelected(result);
                                        },
                                        child: Icon(Icons.add)
                                    ),
                                    FlatButton(
                                        onPressed: () async {
                                          var barCode = await BarcodeScanner.scan();
                                          if (barCode == null) return;
                                          var result = ProductStore.products.firstWhere((product) => product.barCode == barCode, orElse: () => null);
                                          if (result == null){
                                            await showMessageDialog(context, title: "ئەسكەرتىش", content: "نۆۋەتتىكى تاياقچە كودى '${barCode}' بولغان تاۋار تاۋارلار تىزىملىكىدىن تىپىلمىدى، ئاۋال بۇ تاۋار ئۇچۇرىنى تىزىملاپ ئاندىن قايتا سىناپ بىقىڭ.");
                                            return;
                                          }
                                          productSelected(result);
                                        },
                                        child: Icon(Icons.camera_enhance)
                                    ),
                                  ],
                                )),
                              Divider()).items
                      ),
                      isExpanded: productPanelExpanded)
                ],
              )
            ],
          ),
        ),
        Padding(
          padding: EdgeInsets.all(10.0),
          child: ExpansionPanelList(
            children: [
              ExpansionPanel(
                  headerBuilder: (context, expanded) => Container(
                    child: Text("ئەكىرمەكچى بولغان ئامبار"),
                    alignment: Alignment(1.0, 0.0),
                    padding: EdgeInsets.symmetric(horizontal: 15.0),
                  ),
                  body: Padding(
                    padding: EdgeInsets.all(15.0),
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          child: Text("ئامبار"),
                        ),
                        RaisedButton(
                          child: Text(selectedWareHouse?.name ?? "ئامبار تاللاڭ"),
                          onPressed: () async {
                            var result = await Navigator.of(context).push<WareHouse>(MaterialPageRoute(builder: (context) => WareHousePageStateless(selectionMode: true,)));
                            if (result != null){
                              setState(() {
                                selectedWareHouse = result;
                              });
                            }
                          },
                        )
                      ],
                    ),
                  ),
                isExpanded: wareHousePanelExpanded
              ),
            ],
            expansionCallback: (index, expanded){
              setState(() {
                wareHousePanelExpanded = !wareHousePanelExpanded;
              });
            },
          ),
        ),
        SizedBox(
          height: 100.0,
        )
      ]),
    );
  }

  Future<void> showFillParameterDialog(BuildContext context, DialogResult<ProductDetailAtPurchaseOrSell> data) async {
    TextEditingController textFieldCountController = TextEditingController(text: data.data.count?.toString());
    TextEditingController textFieldInPriceController = TextEditingController(text: data.data.inPrice?.toString());
    TextEditingController textFieldSellController = TextEditingController(text: data.data.sellPrice?.toString());

    TextEditingController textFieldMakeDateController = TextEditingController();
    if (data.data.makeDate != null){
      textFieldMakeDateController.text = toDate(data.data.makeDate);
    }
    TextEditingController textFieldSaveDaysController = TextEditingController(text: data.data.saveDays?.toString());

    bool showMoreContent = false;

    return await showDialog(context: context, barrierDismissible: false, builder: (context) =>
        EmbeddableStatefulWidget((context, state) =>
            AlertDialog(
              title: Text("مال ئۇچۇرلىرىنى كىرگۈزۈڭ"),
              content: Wrap(
                direction: Axis.horizontal,
                children: <Widget>[
                  TextField(
                    controller: textFieldCountController,
                    keyboardType: TextInputType.numberWithOptions(
                        signed: true, decimal: true
                    ),
                    decoration: InputDecoration(
                        labelText: "مىقدارىنى كىرگۈزۈڭ",
                        hintText: "دانە ياكى كىلوگىرام دىگەندەك"
                    ),
                  ),
                  TextField(
                    keyboardType: TextInputType.numberWithOptions(
                        decimal: true, signed: true
                    ),
                    decoration: InputDecoration(
                        labelText: "ئەكىرىش باھاسىنى كىرگۈزۈڭ",
                        hintText: "ئەكىرىش باھاسى"
                    ),
                    controller: textFieldInPriceController,
                  ),
                  TextField(
                    keyboardType: TextInputType.numberWithOptions(
                        decimal: true, signed: true
                    ),
                    decoration: InputDecoration(
                        labelText: "سىتىش باھاسىنى كىرگۈزۈڭ",
                        hintText: "سىتىش باھاسى"
                    ),
                    controller: textFieldSellController,
                  ),
                  ExpansionPanelList(
                    expansionCallback: (index, expanded) {
                      state.setState(() {
                        showMoreContent = !showMoreContent;
                      });
                    },
                    children: [
                      ExpansionPanel(
                          headerBuilder: (context, expanded) => Center(
                            child: Text("تىخىمۇ كۆپ تاللانمىلار"),
                          ),
                          body: Padding(
                              padding: EdgeInsets.symmetric(horizontal: 10),
                            child: Wrap(
                              children: <Widget>[
                                Row(
                                  children: <Widget>[
                                    Expanded(
                                      child: TextField(
                                        keyboardType: TextInputType.numberWithOptions(
                                            decimal: true, signed: true
                                        ),
                                        decoration: InputDecoration(
                                            labelText: "ئىشلەپ چىقىرىلغان ۋاقتى",
                                            hintText: "ئىشلەپ چىقىرىلغان ۋاقتى"
                                        ),
                                        controller: textFieldMakeDateController,
                                        enabled: false,
                                      ),
                                    ),
                                    IconButton(icon: Icon(Icons.date_range),
                                        onPressed: () async {
                                          data.data.makeDate = await showDatePicker(context: context, initialDate: DateTime.now().add(Duration(days: -10)), firstDate: DateTime(1917), lastDate: DateTime.now());
                                          if (data.data.makeDate != null)
                                            textFieldMakeDateController.text = toDate(data.data.makeDate);
                                        }
                                    )
                                  ],
                                ),
                                TextField(
                                  keyboardType: TextInputType.numberWithOptions(
                                      decimal: true, signed: true
                                  ),
                                  decoration: InputDecoration(
                                      labelText: "ساقلاش مۇددىتى(كۈن)",
                                      hintText: "ساقلاش مۇددىتى"
                                  ),
                                  controller: textFieldSaveDaysController,
                                ),
                              ],
                            ),
                          ),
                          isExpanded: showMoreContent),
                    ],
                  ),
                ],
              ),
              actions: <Widget>[
                FlatButton(onPressed: () {
                  setState(() {
                    if (textFieldCountController.text == "")
                      textFieldCountController.text = "0";
                    var count = 0.0;

                    try {
                      count = num.parse(textFieldCountController.text).toDouble() ?? 0.0;
                    }
                    catch (exception) {
                      textFieldCountController.clear();
                    }
                    if (!(count > 0)) return;
                    data.data.count = count;

                    try {
                      data.data.inPrice = num.parse(textFieldInPriceController.text).toDouble() ?? 0.0;
                    }
                    catch (exception) {
                      textFieldInPriceController.clear();
                      return;
                    }

                    try {
                      data.data.sellPrice = num.parse(textFieldSellController.text).toDouble() ?? 0.0;
                    }
                    catch (exception) {
                      textFieldSellController.clear();
                      return;
                    }

                    try {
                      data.data.saveDays = num.parse(textFieldSaveDaysController.text).toInt() ?? 0;
                    }
                    catch (exception) {
                      textFieldSellController.clear();
                      return;
                    }


                    data.success = true;
                    Navigator.of(context).pop();
                  });
                }, child: Text("جەزىملەشتۈرۈش"))
              ],
            ), (state) {})
    );
  }

  Future<void> showConfirmDialog(PurchaseOrder order) async {
    order.amount = 0.0;
    order.products.forEach((item) => order.amount += item.inPrice * item.count);
    bool onCredit = false;

    TextEditingController actualMoney = TextEditingController(text: order.amount.toString());

    await showDialog(context: context, barrierDismissible: false, builder: (context)=> Directionality(textDirection: TextDirection.rtl, child: EmbeddedWidget(
      initEvent: (state){

      },
      widgetBuilder: (context, state){
        return AlertDialog(
          title: Text("ھىساب ئۈزۈش"),
          content: Wrap(
            children: <Widget>[
              Padding(padding: EdgeInsets.all(0.0), child: AnimatedContainer(
                duration: Duration(milliseconds: 300),
                child: Column(children: <Widget>[
                  Row(children: <Widget>[
                    Text("ئومومى سوممىسى: "),
                    Text(order.amount.toString(),),
                  ],),
                  TextField(
                    decoration: InputDecoration(
                      hintText: "ئەمەلىي سومما",
                      labelText: "ئەمەلىي سوممىسى",
                    ),
                    keyboardType: TextInputType.numberWithOptions(signed: true, decimal: true),
                    controller: actualMoney,
                    onChanged: (text){
                      var number = num.parse(text).toDouble();
                      if (number >= order.amount)
                        state.setState(() {
                          onCredit = false;
                          if (number > order.amount)
                            actualMoney.text = order.amount.toString();
                        });
                      else
                        state.setState(() {
                          onCredit = true;
                        });
                    },
                  ),
                  SizedBox(height: 20.0,),

                  Visibility(
                    visible: onCredit,
                    child: Row(
                      children: <Widget>[
                        Expanded(child: Text("قەرىز قايتۇرۇش ۋاقتى")),
                        Text(toDate(order.repayDate)),
                        IconButton(icon: Icon(Icons.access_time), onPressed: () async {
                          var date = await showDatePicker(context: context, initialDate: DateTime.now().add(Duration(days: 1)), firstDate: DateTime.now(), lastDate: DateTime.now().add(Duration(days: 360 * 5)));
                          if (date != null) {
                            state.setState((){
                              order.repayDate = date;
                            });
                          }
                        },
                      )
                    ],
                  ),)
                ],),
              ),)
            ],
          ),
          actions: <Widget>[
            FlatButton(child: Text("جەزىملەشتۈرۈش"), onPressed: (){

              try {
                order.sAmount = num.parse(actualMoney.text).toDouble();
              }
              catch (exception){
                showMessageDialog(context, title: "ئەسكەرتىش", content: "ئەمەلىي سوممىسىنى كىرگۈزۈڭ");
                return;
              }

              if ((order.sAmount ?? 0.0) < order.amount && order.repayDate == null){
                showMessageDialog(context, title: "ئەسكەرتىش", content: "قەرىز قايتۇرۇش ۋاقتىنى كىرگۈزۈڭ");
                return;
              }

              if (selectedWareHouse == null){
                showMessageDialog(context, title: "ئەسكەرتىش", content: "ئامبار تاللاڭ");
                return;
              }

              if (order.products.length == 0){
                showMessageDialog(context, title: "ئەسكەرتىش", content: "ئەكىرمەكچى بولغان تاۋارلارنى تاللاڭ");
                return;
              }

              if (selectedSupplier == null && canSelectPurchase){
                showMessageDialog(context, title: "ئەسكەرتىش", content: "مال تەمىنلىگۈچى تاللاڭ");
                return;
              }

              order.supplier = canSelectPurchase ? selectedSupplier?.id ?? 0 : 0;
              order.supplierName = selectedSupplier?.name ?? "";
              order.time = DateTime.now();
              order.products.forEach((item) => item.warehouse = selectedWareHouse.id);
              order.employee = AccountStore.signInResult.id;
              order.employeeName = AccountStore.signInResult.name;

              globalBus.publish(Events.PURCHASE_INSERT_REQUEST, order);
              Navigator.of(context).pop(null);
            }),
          ],
        );
      }
    )));
//    globalBus.publish(Events.PURCHASE_INSERT_REQUEST, order);
  }
}


